#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import uuid
import os
from wfs.function.produce_pdf import th, th2, by_pdf, by_form_pdf
import threading
from datetime import datetime, timedelta
from functools import wraps
from wfs.models import *
from wfs.serializers import *
from wfs.serializers import RoleSerializer
from django.db import transaction
from django.db.models import Count, Q
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import render
from method.method import *
from rest_framework import generics
from rest_framework import mixins, authentication
from rest_framework import mixins, permissions
from rest_framework import renderers
from rest_framework import status
from rest_framework.decorators import api_view, permission_classes
from rest_framework.response import Response
from django.views.decorators.csrf import csrf_exempt
from files.method import change_status,reject_status

null = ""
from  tb_forms.functions.log import log


def wrapp(func):
    """
        Response 跨域裝飾器
    """

    @wraps(func)
    def wrappde(*args, **kwargs):
        data = func(*args, **kwargs)
        re = Response(data, data['status'])
        re['Access-Control-Allow-Origin'] = '*'
        re["Access-Control-Allow-Credentials"] = "true"
        re['Content-Type'] = 'application/json'
        return re

    return wrappde


def Resp(data, s):
    re = Response(data, s)
    re['Access-Control-Allow-Origin'] = '*'
    re["Access-Control-Allow-Credentials"] = "true"
    re['Content-Type'] = 'application/json'
    return re


# 用於角色表查詢所有及添加
class RoleView(mixins.ListModelMixin, mixins.CreateModelMixin, generics.GenericAPIView):
    queryset = WorkflowRole.objects.all()
    serializer_class = RoleSerializer
    # renderer_classes = (renderers.StaticHTMLRenderer,)
    id_list = []
    get_type = 0
    role_tyoe = ""

    def get(self, request, *args, **kwargs):
        self.get_type = int(request.GET.get('type', 1))
        self.role_tyoe = request.GET.get('roleType', '')
        key = request.GET.get('key', '')
        if key:
            # 模糊查询数据, 判读获取全部还是获取有用户的角色
            if self.get_type:
                contains_data = WorkflowRole.objects.values('id', 'user2').filter(Q(role__contains=key) |
                                                                                  Q(
                                                                                      user2__user__last_name__contains=key) |
                                                                                  Q(
                                                                                      user2__user__username__contains=key)).exclude(
                    user2=None).distinct()
            else:
                contains_data = WorkflowRole.objects.values('id', 'user2').filter(Q(role__contains=key) |
                                                                                  Q(
                                                                                      user2__user__last_name__contains=key) |
                                                                                  Q(
                                                                                      user2__user__username__contains=key)).distinct()
            # 为空则认为0
            if [i['id'] for i in contains_data]:
                # 添加到全局变量
                self.id_list = [i['id'] for i in contains_data]
            else:
                self.id_list = [0]
        return self.list(request, *args, **kwargs)

    def get_queryset(self):
        role_list = []
        data = super(RoleView, self).get_queryset()
        if self.id_list:
            # 過濾模糊查詢后數據
            data = data.filter(id__in=self.id_list)
        if self.role_tyoe:
            # 過濾角色類型
            data = data.filter(type=self.role_tyoe)
        # 根据type 去过来数据
        if self.get_type:
            for i in data:
                if len(i.user2.all()) and i not in role_list:
                    role_list.append(i)
        else:
            for i in data:
                if i not in role_list:
                    role_list.append(i)
        return role_list

    def post(self, request, *args, **kwargs):
        if not judging_str(request.data['role']):
            if WorkflowRole.objects.filter(role=request.data['role']):
                return Resp({'data': '該角色已存在', 'status': status.HTTP_202_ACCEPTED}, status.HTTP_202_ACCEPTED)
            self.create(request, *args, **kwargs)
            return Resp({'data': '添加成功', 'status': status.HTTP_200_OK}, status.HTTP_200_OK)
        else:
            return Resp({'data': '該角色中不可包含數字', 'status': status.HTTP_202_ACCEPTED}, status.HTTP_202_ACCEPTED)


# 用於角色表單個查詢及更新刪除
class RoleDetailView(mixins.RetrieveModelMixin, mixins.UpdateModelMixin,
                     mixins.DestroyModelMixin, generics.GenericAPIView):
    queryset = WorkflowRole.objects.all()
    serializer_class = RoleSerializer

    def get(self, request, *args, **kwargs):
        return self.retrieve(request, *args, **kwargs)

    def put(self, request, *args, **kwargs):
        return self.update(request, *args, **kwargs)

    def delete(self, request, *args, **kwargs):
        if WFSOrgRole.objects.filter(role_id=kwargs['pk']):
            return Resp({'data': '請先刪除角色中的人員', 'status': status.HTTP_400_BAD_REQUEST}, status.HTTP_200_OK)
        return self.destroy(request, *args, **kwargs)


# 查詢角色與添加用戶關連信息
class RoleUserView(mixins.ListModelMixin, mixins.CreateModelMixin, generics.GenericAPIView, mixins.DestroyModelMixin):
    queryset = WFSOrgRole.objects.all()
    serializer_class = RoleOrgSerializer

    def get(self, request, *args, **kwargs):
        role_id = request.GET.get('id', '')
        if role_id:
            return Resp(WFSOrgRole.objects.values('id', 'user__username', 'user__last_name', 'role__role').filter(
                role_id=role_id), status.HTTP_200_OK)
        else:
            return Resp(WFSOrgRole.objects.values('id', 'user__username', 'user__last_name', 'role__role'),
                        status.HTTP_200_OK)

    def post(self, request, *args, **kwargs):
        # if self.queryset.filter(role_id=request.data['role'], user_id=request.data['user']):
        #     return Resp({'data':'该用户已在本角色内','status':status.HTTP_202_ACCEPTED},status.HTTP_202_ACCEPTED)
        user_list = eval(request.data['user'])
        index = 0
        request.data._mutable = True  # QueryDict对象設置為可修改（因為服務器與本地差異）
        if WorkflowRole.objects.filter(id=request.data['role'])[0].type != "general":
            if self.queryset.filter(role_id=request.data['role']):
                return Resp({'data': "該角色內無法再添加人員", 'status': status.HTTP_202_ACCEPTED}, status.HTTP_202_ACCEPTED)
            elif len(user_list) > 1:
                return Resp({'data': "該角色只能添加一個人員", 'status': status.HTTP_202_ACCEPTED}, status.HTTP_202_ACCEPTED)
        for i in user_list:
            request.data.update({"user": i})  # 對QueryDict对象 重新賦值
            if not self.queryset.filter(role_id=request.data['role'], user_id=request.data['user']):
                self.create(request, *args, **kwargs)
            else:
                index += 1
        return Resp({'data': '添加成功（包含%s已添加的人員）' % str(index) if index else "添加成功", 'status': status.HTTP_200_OK},
                    status.HTTP_200_OK)

    # def perform_create(self, serializer):
    #      serializer.save(role=self.request.workflow_role)
    def delete(self, request, *args, **kwargs):
        roleUserList = eval(request.GET["roleUserList"])
        if not roleUserList:
            return Resp({'data': "刪除人不能為空", 'status': status.HTTP_202_ACCEPTED}, status.HTTP_202_ACCEPTED)
        for i in roleUserList:
            self.kwargs["pk"] = i
            try:
                self.destroy(request, *args, **kwargs)
            except:
                pass
        return Resp({'data': "刪除成功", 'status': status.HTTP_200_OK}, status.HTTP_200_OK)


# 角色與添加用戶關連信息更新刪除
class RoleUserDetailView(mixins.RetrieveModelMixin, mixins.UpdateModelMixin,
                         mixins.DestroyModelMixin, generics.GenericAPIView):
    queryset = WFSOrgRole.objects.all()
    serializer_class = RoleOrgSerializer

    def get(self, request, *args, **kwargs):
        return Resp(WFSOrgRole.objects.values('id', 'user__username', 'user__last_name', 'role__role').filter(
            id=self.kwargs['pk']), status.HTTP_200_OK)

    def put(self, request, *args, **kwargs):
        return self.update(request, *args, **kwargs)

    def delete(self, request, *args, **kwargs):
        return self.destroy(request, *args, **kwargs)


def flow(request, pk):
    content = {}
    if request.method == "GET":
        try:
            record = Workflowrecord.objects.filter(workflow_id=pk).all()
            for i in record:
                pass
        except Exception as e:
            pass
        finally:
            pass


# @login_check

@api_view(http_method_names=["GET", "PUT", "POST", "DELETE"])
@wrapp
@csrf_exempt
def approval_record(request):
    """
    申請人簽核記錄
    :param request:
    :return:
    """
    content = {}
    if request.method == 'GET':
        try:
            userName = request.user.username  # request.session['username']
            wkRecord = Workflowrecord.objects.filter(applicant=userName)
            content['data'] = []
            for record in wkRecord:
                userList = []
                for i in WorkflowApprovalRecord.objects.filter(workflow_record_id=record.id).all().order_by(
                        'order_number'):
                    name = User.objects.filter(username=i.approver).values('last_name', 'last_name')[0]
                    userList.append([i.order_number, name['last_name'], i.start_time, i.end_time, i.action])
                content['data'].append({'no': record.no, 'record': userList})
            content['status'] = status.HTTP_200_OK
        except Exception as e:
            content['message'] = str(e)
            content['status'] = status.HTTP_500_INTERNAL_SERVER_ERROR
        finally:
            return content


@api_view(http_method_names=["GET", "PUT", "POST", "DELETE"])
@wrapp
@csrf_exempt
def worflow_name(request):
    content = {}
    if request.method == "GET":
        try:
            snippets = Workflow.objects.values().filter(enabled=1)
            data = []
            for i in snippets:
                i['rectime'] = i['rectime'].strftime('%Y-%m-%d %H:%M:%S')
                i['update_time'] = i['update_time'].strftime('%Y-%m-%d %H:%M:%S') if i['update_time'] else ''
                end = Workflownode.objects.filter(workflow_id=i['id'], order_number=i['end'])
                start = Workflownode.objects.filter(workflow_id=i['id'], order_number=i['start'])
                if end and start:
                    i['len'] = i['end']
                    i['start'] = start[0].name
                    i['end'] = end[0].name
                    data.append(i)
                else:
                    i['len'] = ''
                    i['start'] = ''
                    i['end'] = ''
                    data.append(i)
            content['data'] = data
            content['status'] = status.HTTP_200_OK
        except Exception as e:
            content['status'] = status.HTTP_404_NOT_FOUND
            content['message'] = str(e)
        finally:
            return content
    if request.method == "POST":
        try:
            data = request.data['title']
            title = Workflow.objects.filter(name=data).exclude(enabled=13)
            if not title:
                content['data'] = "成功"
                content['status'] = status.HTTP_200_OK
                return content
            else:
                content['data'] = "已有重複的名字"
                content['status'] = status.HTTP_202_ACCEPTED
                return content
        except Exception as e:
            content['data'] = str(e)
            content['status'] = status.HTTP_202_ACCEPTED
            return content


from tb_forms.models import TbForms


# @login_check
@api_view(http_method_names=["GET", "PUT", "POST", "DELETE"])
@wrapp
@csrf_exempt
def workflow(request):
    """
    創建工作流
    :param request:
    :return:
    """
    content = {}
    if request.method == "POST":
        try:
            role_number = 0
            userName = request.user.username
            name = request.user.last_name
            workflowData = eval(request.data['workflow'])
            # enabled = int(request.data['enabled'])
            if workflowData:
                try:
                    with transaction.atomic():
                        if not Workflow.objects.filter(name=workflowData['title']).exclude(enabled=13):
                            # workflow = Workflow.objects.create(name=workflowData['title'],founder=userName,username=name,enabled=enabled)
                            workflow = Workflow.objects.create(name=workflowData['title'], founder=userName,
                                                               username=name, enabled=9,
                                                               workflow_type=workflowData['type'])
                            index = 1
                            for node in workflowData['data']:
                                userList = []
                                if node['property']['userRoles']:
                                    for i in node['property']['userRoles']:
                                        if judging_str(i):
                                            wor = TbWorkflowRole2.objects.filter(username=i)
                                            if wor:
                                                roleID = TbWorkflowRole2.objects.create(username=i)
                                                userList.append(roleID.id)
                                            else:
                                                userList.append(wor[0].id)
                                        else:
                                            userList.append(i)
                                Workflownode.objects.create(name=node['name'], order_number=index,
                                                            property=node['property'],
                                                            workflow_id=workflow.id)
                                index += 1
                            Workflow.objects.filter(id=workflow.id).update(end=index - 1, start=1,
                                                                           rectime=datetime.now())
                            content['status'] = status.HTTP_201_CREATED
                            content['data'] = '創建成功'
                            return content
                        else:
                            content['status'] = status.HTTP_202_ACCEPTED
                            content['data'] = '工作流已存在'
                            return content
                except WorkflowError as e:
                    content['status'] = status.HTTP_202_ACCEPTED
                    content['data'] = str(e)
                    return content
            content['status'] = status.HTTP_202_ACCEPTED
            content['data'] = '請填寫內容'
        except Exception as e:
            content['status'] = status.HTTP_202_ACCEPTED
            content['message'] = str(e)
        finally:
            return content
    if request.method == "GET":
        try:
            snippets = Workflow.objects.values().exclude(enabled=13)
            data = []
            for i in snippets:
                i['rectime'] = i['rectime'].strftime('%Y-%m-%d %H:%M:%S')
                i['update_time'] = i['update_time'].strftime('%Y-%m-%d %H:%M:%S') if i['update_time'] else ''
                end = Workflownode.objects.filter(workflow_id=i['id'], order_number=i['end'])
                start = Workflownode.objects.filter(workflow_id=i['id'], order_number=i['start'])
                if end and start:
                    i['len'] = i['end']
                    i['start'] = start[0].name
                    i['end'] = end[0].name
                    data.append(i)
                else:
                    i['len'] = ''
                    i['start'] = ''
                    i['end'] = ''
                    data.append(i)
            content['data'] = data
            content['status'] = status.HTTP_200_OK
        except Exception as e:
            content['status'] = status.HTTP_404_NOT_FOUND
            content['message'] = str(e)
        finally:
            return content
    if request.method == "PUT":
        try:
            workflow_id = request.data['id']
            enabled = request.data['enabled']

            # if enabled != '0' and enabled != '1':
            #     content['status'] = status.HTTP_202_ACCEPTED
            #     content['data'] = '歡迎加入BEACON'
            #     return content
            # if Workflowrecord.objects.filter(workflow_id=workflow_id):
            #     content['status'] = status.HTTP_202_ACCEPTED
            #     content['data'] = '該模板正在使用無法修改'
            #     return content
            if Workflow.objects.filter(id=workflow_id)[0].update_type == "N":
                content['status'] = status.HTTP_202_ACCEPTED
                content['data'] = '該工程模板無法修改'
                return content
            if str(Workflow.objects.filter(id=workflow_id)[0].enabled) == str(9) and enabled == "9":
                content['status'] = status.HTTP_202_ACCEPTED
                content['data'] = '草稿無法棄用'
                return content
            else:
                if enabled == "1" and Workflow.objects.filter(workflow_type="other", id=workflow_id):
                    node = Workflownode.objects.filter(workflow_id=workflow_id)
                    if node:
                        for i in node:
                            data = eval(i.property)
                            if not data["userRoles"] and not data["userMode"] and not data['upLevel'] and not data[
                                'lowerToLevel'] and not data['upToLevel']:
                                content['status'] = status.HTTP_202_ACCEPTED
                                content['data'] = '請完善模板后再啟用'
                                return content
                    else:
                        content['status'] = status.HTTP_202_ACCEPTED
                        content['data'] = '請完善模板后再啟用'
                        return content
                if enabled != 1:
                    TbForms.objects.filter(workflow_id=workflow_id).update(workflow_id=None, status=0)
                Workflow.objects.filter(id=workflow_id).update(enabled=enabled)
                content['status'] = status.HTTP_200_OK
                content['data'] = '啟用成功' if enabled == "1" else '棄用成功'
                return content
        except Exception as e:

            content['status'] = status.HTTP_202_ACCEPTED
            content['data'] = str(e)
            return content


@api_view(http_method_names=["GET", "PUT", "POST", "DELETE"])
@wrapp
@csrf_exempt
def workflow_one(request, pk):
    content = {}
    user = request.user
    if request.method == "PUT":
        try:
            workflowData = eval(request.data['workflow'])
            workflowID = pk
            # if Workflowrecord.objects.filter(workflow_id=pk):
            #     content['status'] = status.HTTP_202_ACCEPTED
            #     content['data'] = '該模板正在使用無法修改'
            #     return content
            if not workflowData['data']:
                content['status'] = status.HTTP_202_ACCEPTED
                content['data'] = '请完善該模板'
                return content
            Workflow.objects.filter(id=workflowID).update(name=workflowData['title'], update_time=datetime.now(),
                                                          founder=user.username, username=user.last_name, start=1,
                                                          workflow_type=workflowData['type'],
                                                          end=len(workflowData['data']))
            node = Workflownode.objects.filter(workflow_id=workflowID)
            index = 1
            if len(node) == len(workflowData['data']):  # 傳入值數量與數據相同 只做修改動作
                for node in workflowData['data']:
                    Workflownode.objects.filter(workflow_id=workflowID, order_number=index).update(name=node['name'],
                                                                                                   property=by_username(
                                                                                                       node[
                                                                                                           'property']),
                                                                                                   order_number=index)
                    index += 1

            elif len(node) < len(workflowData['data']):  # 傳入數據總和比數據庫多  做修改新增動作
                for row in range(len(node)):  # 修改數據庫存在數據
                    Workflownode.objects.filter(workflow_id=workflowID, order_number=index).update(
                        name=workflowData['data'][row]['name'],
                        property=by_username(workflowData['data'][row]['property']),
                        order_number=index)
                    index += 1
                for i in range(len(node), len(workflowData['data'])):  # 新增數據
                    Workflownode.objects.create(name=workflowData['data'][i]['name'], order_number=index,
                                                property=by_username(workflowData['data'][i]['property']),
                                                workflow_id=workflowID)
                    index += 1
            elif len(node) > len(workflowData['data']):
                for row in range(0, len(workflowData['data'])):  # 修改數據庫存在數據
                    Workflownode.objects.filter(workflow_id=workflowID, order_number=index).update(
                        name=workflowData['data'][row]['name'],
                        property=by_username(workflowData['data'][row]['property']),
                        order_number=index)
                    index += 1
                for i in range(len(workflowData['data']), len(node)):  # 刪除動作
                    Workflownode.objects.filter(order_number=index, workflow_id=workflowID).delete()
                    index += 1
            # Workflow.objects.filter(id=workflowID).update(end=index-1,start=1,rectime=datetime.now())
            content['status'] = status.HTTP_200_OK
            content['data'] = '修改成功'
        except Exception as e:
            content['status'] = status.HTTP_400_BAD_REQUEST
            content['message'] = str(e)
        finally:
            return content
    if request.method == "GET":
        try:
            snippets = Workflow.objects.filter(id=pk).values("id", "name", 'workflow_type')
            if snippets:
                list = []
                node = Workflownode.objects.filter(workflow_id=pk).all()
                for i in node:
                    prope = eval(i.property)
                    userList = []
                    if prope['userRoles']:
                        for row in prope['userRoles']:
                            if judging_str(row):
                                role = TbWorkflowRole2.objects.filter(id=row)
                                if role:
                                    userList.append(role[0].username)
                            else:
                                userList.append(row)
                    prope['userRoles'] = userList
                    list.append({"id": i.id, "name": i.name, "property": str(prope)})
                content['data'] = {'id': snippets[0]['id'], 'title': snippets[0]['name'],
                                   'workflow_type': snippets[0]['workflow_type'], 'data': list}
                content['status'] = status.HTTP_200_OK
                return content
            content['status'] = status.HTTP_400_BAD_REQUEST
            content['message'] = '該記錄不存在'
        except Exception as e:
            content['status'] = status.HTTP_400_BAD_REQUEST
            content['message'] = str(e)
        finally:
            return content
    if request.method == "DELETE":
        try:
            if pk:
                if Workflow.objects.filter(id=pk)[0].update_type == "N":
                    content['status'] = status.HTTP_202_ACCEPTED
                    content['data'] = '該工程模板無法刪除'
                    return content
                Workflow.objects.filter(id=pk).update(enabled=13)
                # Workflownode.objects.filter(workflow_id=pk).delete()
                content['data'] = '刪除成功'
                content['status'] = status.HTTP_200_OK
                return content
            content['message'] = '错误请求'
            content['status'] = status.HTTP_400_BAD_REQUEST
        except Exception as e:
            content['status'] = status.HTTP_400_BAD_REQUEST
            content['message'] = str(e)
        finally:
            return content


import re


@api_view(http_method_names=["GET", "PUT", "POST", "DELETE"])
@wrapp
@csrf_exempt
def case_workflow(request):
    """
    實例化
    :param request:
    :return:
    """
    content = {}
    jon = request.user.username
    name = request.user.last_name
    # if request.method == 'GET':
    #     try:
    #         workflowArray = {}
    #         workflowDat = Workflowrecord.objects.values('id','no','desc','applicant').filter(applicant=jon,status=0)
    #         workflowList = []
    #         for workflow in workflowDat:
    #             groupList = []
    #             workflow['groupList'] = []
    #             for group in NodeGroup.objects.values('id','name').filter(workflowrecord_id=workflow['id']).order_by('order_number'):
    #                 group['nodeList'] = []
    #                 for node in NodeCase.objects.values('id','approver','user_mode','user_role_list').filter(group=group['id']).order_by('order_number'):
    #                     group['nodeList'].append(node)
    #                 groupList.append(group)
    #             workflow['groupList'].append(groupList)
    #             workflowList.append(workflow)
    #         content['data'] =workflowList
    #         content['status'] = status.HTTP_200_OK
    #     except Exception as e:
    #         content['status'] = status.HTTP_404_NOT_FOUND
    #         content['message'] = str(e)
    if request.method == 'GET':
        # try:
        from tb_forms.models import TbForms
        if request.GET.get('type', ''):
            try:
                data = Workflow.objects.filter(flowchart=request.GET.get('type', ''))[0].id
                forms_data = TbForms.objects.filter(workflow_id=data)
            except Exception as e:
                content['status'] = status.HTTP_202_ACCEPTED
                content['message '] = str(e)  # "未找到該流程"
                return content
        else:
            data = request.GET.get('id', '')
            if not data:
                content['status'] = status.HTTP_202_ACCEPTED
                content['message '] = "請選擇要實例化的表單"
                return content
            forms_data = TbForms.objects.filter(id=data)
        if not forms_data:
            content['status'] = status.HTTP_202_ACCEPTED
            content['message'] = "未找到該表單"
            return content
        wfl = forms_data[0].workflow_id
        user_org = UserOrg.objects.filter(user_id=request.user.id).values('org__org_name', 'org_id')
        case_data1 = []
        workflow_type = Workflow.objects.filter(id=forms_data[0].workflow_id)[0].workflow_type
        if len(user_org) <= 1 or workflow_type == "self":
            case_data = case(request.user, '', '', forms_data[0].workflow_id, '', data)
            if len(case_data["case"]) >= 2:
                for i in range(0, len(case_data["case"]) - 2):
                    if len(case_data["case"][i]["node"]["user_role"]) == 0 and string_comparison(
                            case_data["case"][i + 1]["node"]["user_mode"], "ByLastNode"):
                        case_data["status"] = "error"
                        break
            case_data["status"] = "normal"
            case_data1.append(case_data)
        else:
            for i in user_org:
                case_data = case(request.user, '', i["org_id"], forms_data[0].workflow_id, '', data)
                if len(case_data["case"]) >= 2:
                    for i in range(0, len(case_data["case"]) - 2):
                        if len(case_data["case"][i]["node"]["user_role"]) == 0 and string_comparison(
                                case_data["case"][i + 1]["node"]["user_mode"], "ByLastNode"):
                            case_data["status"] = "error"
                            break
                case_data["status"] = "normal"
                case_data1.append(case_data)

        content['data'] = case_data1
        content['status'] = status.HTTP_200_OK
        # except Exception as e:
        #     content['status'] = status.HTTP_202_ACCEPTED
        #     content['message'] = str(e) #"表單實例化失敗，請聯繫管理員查看"
    return content


# @login_check
@api_view(http_method_names=["GET", "PUT", "POST", "DELETE"])
@wrapp
@csrf_exempt
def workflow_case_one(request):
    content = {}
    if request.method == 'GET':
        try:
            user = request.user.id
            user_org = UserOrg.objects.filter(user_id=user).values('org__org_name', 'org_id')
            if user_org.count() <= 1:
                content['data'] = []
            else:
                content['data'] = [i for i in user_org]
            content['status'] = status.HTTP_200_OK
        except Exception as e:
            content['status'] = status.HTTP_404_NOT_FOUND
            content['message'] = str(e)
        finally:
            return content
    return content


from tb_forms import models


@api_view(http_method_names=["GET", "PUT", "POST", "DELETE"])
@wrapp
def bacth_app(request):
    content = {}
    user = request.user.username
    if request.method == 'POST':
        import requests
        try:

            with transaction.atomic():
                record = eval(request.POST['recordList'])
                action = request.POST['action']
                token = request.META["HTTP_X_CSRFTOKEN"]
                IP = request.META["HTTP_HOST"]
                app = "表單編號："
                no, error = '', ''
                for i in record:
                    appr = WorkflowApprovalRecord.objects.filter(workflow_record_id=i, approver=user, status=0)
                    if appr:
                        appType = \
                            models.TbApplyform.objects.filter(wrecord=appr[0].workflow_record_id).values('card_id',
                                                                                                         'apply_type')[
                                0]
                        if appType['apply_type'] == 'true':
                            no = appType['card_id'] + ','
                            continue
                        # message = threading.Thread(
                        #     target=
                        data = requests.post(settings.DOWNLOAD_URL + '/api/workflow_approval',
                                             data={'id': appr[0].id, 'action': action}, headers={'X-CSRFToken': token})
                        if data.json()['status']:
                            error = 'True'

                            # message.setDaemon(True)
                            # message.start()
                if no:
                    content['data'] = '批量簽核成功(' + app + no + '只能APP簽核,含有指定下一人簽核無法簽核)'
                else:
                    content['data'] = '批量簽核成功' if not error else '批量簽核成功(無法簽核指定下一人簽核)'
                content['status'] = status.HTTP_200_OK
                return content
        except WorkflowError:
            content['data'] = '批量簽核失敗'
            content['status'] = status.HTTP_202_ACCEPTED
            return content


@api_view(http_method_names=["GET", "PUT", "POST", "DELETE"])
@wrapp
@csrf_exempt
def workflow_approval(request):
    """
    簽核
    :param request:
    :return:
    """
    content = {}

    username = str(request.user.username)
    if request.method == "POST":
            node_id = request.data
            username = str(request.user.username)
        # try:
            nodeData = WorkflowApprovalRecord.objects.filter(id=node_id['id'])
            if not nodeData:
                content['data'] = '未找到該記錄'
                content['status'] = status.HTTP_202_ACCEPTED
                return content
            elif nodeData[0].approver != username:
                content['data'] = '該簽核記錄不屬於你'
                content['status'] = status.HTTP_202_ACCEPTED
                return content
            elif nodeData[0].status == '1':
                content['data'] = '該簽核記錄已被簽核'
                content['status'] = status.HTTP_202_ACCEPTED
                return content
            index = nodeData[0].order_number
            nextID = nodeData[0].next
            record_count = WorkflowApprovalRecord.objects.filter(next=nextID, order_number=index, status=0).count()
            nodeData.update(status=1)

            with transaction.atomic():
                img = ''
                rec = Workflowrecord.objects.filter(id=nodeData[0].workflow_record_id).values('signature_graph', 'id')
                if nodeData[0].signature:
                    pass
                else:
                    if rec:
                        img = User.objects.filter(username=username).values('sign')[0]['sign']
                    else:
                        img = ""
                desc = node_id['desc'] if 'desc' in node_id else ''
                usernames = node_id['username'] if 'username' in node_id else ""

                if request.FILES.get('file'):
                    filename = request.FILES.get('file')
                    path = settings.MEDIA_ROOT + settings.WORKFLOW_IMG_URL
                    formfile = WorkflowApprovalRecord.objects.filter(id=node_id['id'])
                    name = ''
                    if filename == None:
                        fileurl = None
                    else:
                        with open(path.replace('//', '/') + filename.name, 'wb') as flhd:
                            flhd.write(filename.read())
                            flhd.close()
                            name = settings.WORKFLOW_IMG_URL2 + filename.name
                    if formfile:
                        img = name
                    else:
                        return {"status": status.HTTP_202_ACCEPTED, 'data': "記錄不存在"}
                elif request.FILES.getlist('filename'):
                    filename = request.FILES.getlist('filename')
                    path = settings.MEDIA_ROOT + settings.WORKFLOW_FILE_URL
                    formfile = WorkflowApprovalRecord.objects.filter(id=node_id['id'])
                    filearray = []
                    if filename == None:
                        fileurl = None
                    else:
                        import io, sys
                        for row in filename:
                            rows = os.path.splitext(row.name)

                            oneFile = rows[0] + "(" + str(uuid.uuid4()) + ")" + rows[1]
                            # fi = open(path.replace('//','/')+oneFile,'wb')
                            # fi.write(row.read())
                            # fi.close()
                            with open(path.replace('//', '/') + oneFile.replace(' ', ''), 'wb') as flhd:
                                flhd.write(row.read())
                                flhd.close()
                            filearray = settings.WORKFLOW_FILE_URL2 + oneFile
                    if formfile:
                        formfile.update(filename=filearray)
                    else:
                        return {"status": status.HTTP_202_ACCEPTED, 'data': "記錄不存在"}
                if '-' not in nextID:
                    if node_id['action'] == "pass":
                        nodeData.update(status=1, action='通過', end_time=datetime.now(), desc=desc, signature=img)
                        ar = WorkflowApprovalRecord.objects.filter(id=nodeData[0].next)[0]
                        d = by_pdf(nodeData[0].workflow_record_id)
                        nodeData.update(pdf=d)
                        WorkflowApprovalRecord.objects.create(start_time=datetime.now(), approver=ar.approver,
                                                              next=ar.next, status=0,
                                                              order_number=index + 1,
                                                              workflow_record_id=ar.workflow_record_id,
                                                              next_approver=ar.next_approver)
                        content['data'] = '通過'
                    elif string_comparison(node_id['action'], "rejected"):
                        nodeData.update(status=1, action='駁回', end_time=datetime.now(), desc=desc, signature=img)
                        d = by_pdf(nodeData[0].workflow_record_id)
                        nodeData.update(pdf=d)
                        Workflowrecord.objects.filter(id=nodeData[0].workflow_record_id).update(status=1,
                                                                                                end_time=datetime.now())
                        content['data'] = '駁回'
                    content['status'] = status.HTTP_200_OK
                    xiaoxituisong(node_id['action'], request.user, nodeData[0].workflow_record_id)
                    return content

                nodePropety = NodeCase.objects.filter(group_id=nextID.split('-')[0],
                                                      order_number=1 if nextID.split('-')[1] == '0' else
                                                      nextID.split('-')[1]).all()[0]
                if record_count > 1:  # 判斷需簽核的條目大於1是
                    if node_id['action'] == "pass":  # 通過
                        if string_comparison(nodePropety.user_mode, 'OneOnly'):
                            # NodeCase.objects.filter(order_number=node_id['order_number'],group_id=node_id['node_id']).update(status='已簽核')
                            next_app = eval(nodeData[0].next_approver) if nodeData[0].next_approver else []
                            user_role_list = eval(nodePropety.user_role_list) if nodePropety.user_role_list else []
                            if usernames in next_app or usernames in user_role_list or (
                                            next_app == [] and user_role_list == []):
                                nodeData.update(status=1, action='通過', end_time=datetime.now(), desc=desc,
                                                signature=img)
                                # 下一個節點及發郵件通知
                                WorkflowApprovalRecord.objects.filter(next=nextID, order_number=index, status=0).update(
                                    status=2, action='通過', end_time=datetime.now())
                                one_approval(nextID, index, nodeData[0].workflow_record_id, usernames)
                                d = by_pdf(nodeData[0].workflow_record_id)

                                if int(Workflowrecord.objects.filter(id=nodeData[0].workflow_record_id).values_list(
                                        'status', flat=True)[0][0]):
                                    change_status(nodeData[0].workflow_record_id,
                                                  [file.split('ST')[1] for file in d])
                                nodeData.update(pdf=d)
                                xiaoxituisong(node_id['action'], request.user, nodeData[0].workflow_record_id)
                                content['data'] = '通過'
                                content['status'] = status.HTTP_200_OK
                                return content
                            elif user_role_list != [] or next_app != []:
                                content['data'] = '請選擇下一節點簽核人'
                                content['status'] = status.HTTP_202_ACCEPTED
                                return content
                            elif (user_role_list != [] or next_app != []) and usernames != "":
                                content['data'] = '該簽核點無簽核列表'
                                content['status'] = status.HTTP_202_ACCEPTED
                                return content
                            elif usernames != "" and (usernames not in next_app or usernames not in user_role_list):
                                content['data'] = '請選擇正確的簽核人'
                                content['status'] = status.HTTP_202_ACCEPTED
                                return content
                        elif string_comparison(nodePropety.user_mode, 'MUSTALL'):
                            # countRecord = WorkflowApprovalRecord.objects.filter(next=nextID,order_number=index).count()
                            nodeData.update(status=1, action='通過', end_time=datetime.now(), desc=desc)
                            d = by_pdf(nodeData[0].workflow_record_id)
                            nodeData.update(pdf=d)
                            if int(Workflowrecord.objects.filter(id=nodeData[0].workflow_record_id).values_list(
                                    'status', flat=True)[0][0]):
                                change_status(nodeData[0].workflow_record_id,
                                              [file.split('ST')[1] for file in d])
                            xiaoxituisong(node_id['action'], request.user, nodeData[0].workflow_record_id)
                            content['data'] = '通過'
                            content['status'] = status.HTTP_200_OK
                            return content

                    elif string_comparison(node_id['action'], "rejected"):  # 駁回
                        approver = Workflowrecord.objects.filter(id=nodeData[0].workflow_record_id)
                        if string_comparison(nodePropety.reject_mode, 'toApplicant'):  # 駁回至申請者
                            WorkflowApprovalRecord.objects.filter(workflow_record_id=nodeData[0].workflow_record_id,
                                                                  next=nextID, order_number=index, status=0).update(
                                status=1, end_time=datetime.now())
                            # Workflowrecord.objects.filter(id=nodeData[0].workflow_record_id)
                            nodeData.update(status=1, action='駁回', end_time=datetime.now(), desc=desc, signature=img)
                            recName = Workflowrecord.objects.all().filter(id=nodeData[0].workflow_record_id)
                            nextRecord = WorkflowApprovalRecord.objects.all().filter(
                                workflow_record_id=nodeData[0].workflow_record_id,
                                order_number=int(nodeData[0].order_number) - 1)
                            if recName[0].applicant == username and nextRecord[0].action == "駁回":
                                Workflowrecord.objects.filter(id=nodeData[0].workflow_record_id).update(status=1,
                                                                                                        end_time=datetime.now())
                            else:
                                if int(node_id['type']):  # 判斷駁回后是否回到駁回者
                                    WorkflowApprovalRecord.objects.create(start_time=datetime.now(),
                                                                          approver=approver[0].applicant,
                                                                          next=node_id['id'], status=0,
                                                                          order_number=index + 1,
                                                                          workflow_record_id=approver[0].id,
                                                                          next_approver=[])
                                else:
                                    WorkflowApprovalRecord.objects.create(start_time=datetime.now(),
                                                                          approver=approver[0].applicant,
                                                                          next=oneNode(approver[0].id, index + 1),
                                                                          status=0,
                                                                          order_number=index + 1,
                                                                          workflow_record_id=approver[0].id,
                                                                          next_approver=[])
                            d = by_form_pdf(nodeData[0].workflow_record_id)
                            nodeData.update(pdf=d)
                            xiaoxituisong(node_id['action'], request.user, nodeData[0].workflow_record_id)
                            reject_status(nodeData[0].workflow_record_id)
                            content['data'] = '駁回成功'
                            content['status'] = status.HTTP_200_OK
                            return content
                            # user_mail('您好,你有1筆員工事務等待簽核',approver[0].applicant,'你的已筆XXXX被駁回請重新申請')
                        elif string_comparison(nodePropety.reject_mode, 'AllowToSelect'):  # 駁回到某個節點組
                            if node_id['username']:
                                toMe = 0
                                WorkflowApprovalRecord.objects.filter(workflow_record_id=nodeData[0].workflow_record_id,
                                                                      next=nextID, order_number=index, status=0).update(
                                    status=100000, end_time=datetime.now())
                                nodeData.update(status=1, action='駁回', end_time=datetime.now(), desc=desc,
                                                signature=img)  # 更新記錄表
                                recName = Workflowrecord.objects.all().filter(id=nodeData[0].workflow_record_id)
                                nextRecord = WorkflowApprovalRecord.objects.all().filter(
                                    workflow_record_id=nodeData[0].workflow_record_id,
                                    order_number=int(nodeData[0].order_number) - 1)
                                if recName[0].applicant == username and nextRecord[0].action == "駁回":
                                    Workflowrecord.objects.filter(id=nodeData[0].workflow_record_id).update(status=1,
                                                                                                            end_time=datetime.now())
                                else:
                                    if node_id['username'] == '0':
                                        oneRecord = WorkflowApprovalRecord.objects.filter(
                                            workflow_record_id=nodeData[0].workflow_record_id).order_by('start_time')[0]
                                        node = [oneRecord]
                                        node_id['username'] = NodeGroup.objects.order_by('order_number')[0].id
                                        toMe = 1
                                    else:
                                        node = NodeCase.objects.filter(group_id=node_id['username'],
                                                                       order_number=1)  # 查找nodecase實例
                                    for i in node:  # 遍歷寫入
                                        if int(node_id['type']):  # 判斷駁回后是否回到駁回者
                                            WorkflowApprovalRecord.objects.create(
                                                workflow_record_id=nodeData[0].workflow_record_id, status=0,
                                                approver=i.approver,
                                                next=node_id['id'],
                                                start_time=datetime.now(), order_number=index + 1)
                                        else:
                                            WorkflowApprovalRecord.objects.create(
                                                workflow_record_id=nodeData[0].workflow_record_id, status=0,
                                                approver=i.approver,
                                                next=oneNode(approver[0].id, index + 1),
                                                start_time=datetime.now(), order_number=index + 1)
                                d = by_form_pdf(nodeData[0].workflow_record_id)
                                nodeData.update(pdf=d)
                                xiaoxituisong(node_id['action'], request.user, nodeData[0].workflow_record_id)
                                reject_status(nodeData[0].workflow_record_id)
                                content['data'] = '駁回成功'
                                content['status'] = status.HTTP_200_OK
                                return content
                            else:
                                content['data'] = '請選擇駁回到指定節點'
                                content['status'] = status.HTTP_202_ACCEPTED
                                return content
                    elif string_comparison(node_id['action'], "forward"):  # 轉呈
                        if string_comparison(nodePropety.forward_mode, 'NoForward'):
                            content['message'] = 'No forward'
                            content['status'] = status.HTTP_202_ACCEPTED
                            return content
                        else:
                            WorkflowApprovalRecord.objects.filter(next=nextID, order_number=index, status=0).update(
                                status=1, end_time=datetime.now(), signature=img)
                            forward_(nextID, nodePropety, nodeData, node_id, index)
                            nodeData.update(status=1, action='轉呈', end_time=datetime.now(), desc=desc)  # 更新記錄表
                            d = by_form_pdf(nodeData[0].workflow_record_id)
                            nodeData.update(pdf=d)
                            xiaoxituisong(node_id['action'], request.user, nodeData[0].workflow_record_id)
                            content['data'] = "簽核成功"
                            content['status'] = status.HTTP_200_OK
                            return content
                    elif string_comparison(node_id['action'], "Abstain"):
                        if string_comparison(nodePropety.user_mode, "action"):
                            nodeData.update(status=1, action='棄權', end_time=datetime.now(), desc=desc, signature=img)
                            # 下一個節點及發郵件通知
                            one_approval(nextID, index, nodeData[0].workflow_record_id, usernames)
                            d = by_form_pdf(nodeData[0].workflow_record_id)
                            nodeData.update(pdf=d)
                            xiaoxituisong(node_id['action'], request.user, nodeData[0].workflow_record_id)
                            content['data'] = '棄權'
                            content['status'] = status.HTTP_200_OK
                            return content
                        else:
                            content['data'] = '該節點無法棄權'
                            content['status'] = status.HTTP_202_ACCEPTED
                            return content
                else:
                    if string_comparison(node_id['action'], "pass"):  # 通過
                        # 簽核
                        next_app = eval(nodeData[0].next_approver) if nodeData[0].next_approver else []
                        user_role_list = eval(nodePropety.user_role_list) if nodePropety.user_role_list else []
                        if usernames in next_app or usernames in user_role_list or (
                                        next_app == [] and user_role_list == []):
                            nodeData.update(status=1, action='通過', end_time=datetime.now(), desc=desc, signature=img)
                            # 下一個節點及發郵件通知
                            one_approval(nextID, index, nodeData[0].workflow_record_id, usernames)
                            d = by_pdf(nodeData[0].workflow_record_id)
                            nodeData.update(pdf=d)
                            if int(Workflowrecord.objects.filter(id=nodeData[0].workflow_record_id).values_list(
                                    'status', flat=True)[0][0]):
                                change_status(nodeData[0].workflow_record_id,
                                              [file.split('ST')[1] for file in d])
                            xiaoxituisong(node_id['action'], request.user, nodeData[0].workflow_record_id)
                            content['data'] = '通過'
                            content['status'] = status.HTTP_200_OK
                            return content
                        elif user_role_list != [] or next_app != []:
                            content['data'] = '請選擇下一節點簽核人'
                            content['status'] = status.HTTP_202_ACCEPTED
                            return content
                        elif (user_role_list != [] or next_app != []) and usernames != "":
                            content['data'] = '該簽核點無簽核列表'
                            content['status'] = status.HTTP_202_ACCEPTED
                            return content
                        elif usernames != "" and (usernames not in next_app or usernames not in user_role_list):
                            content['data'] = '請選擇正確的簽核人'
                            content['status'] = status.HTTP_202_ACCEPTED
                            return content
                    elif string_comparison(node_id['action'], "rejected"):  # 駁回
                        approver = Workflowrecord.objects.filter(id=nodeData[0].workflow_record_id)
                        if string_comparison(nodePropety.reject_mode, 'toApplicant'):  # 駁回至申請者
                            WorkflowApprovalRecord.objects.filter(next=nextID, order_number=index, status=0).update(
                                status=1, end_time=datetime.now())
                            # Workflowrecord.objects.filter(id=nodeData[0].workflow_record_id)
                            nodeData.update(status=1, action='駁回', end_time=datetime.now(), desc=desc, signature=img)
                            recName = Workflowrecord.objects.all().filter(id=nodeData[0].workflow_record_id)
                            nextRecord = WorkflowApprovalRecord.objects.all().filter(
                                workflow_record_id=nodeData[0].workflow_record_id,
                                order_number=int(nodeData[0].order_number) - 1)
                            if recName[0].applicant == username and nextRecord[0].action == "駁回":
                                Workflowrecord.objects.filter(id=nodeData[0].workflow_record_id).update(status=1,
                                                                                                        end_time=datetime.now())
                            else:
                                if int(node_id['type']):  # 判斷駁回后是否回到駁回者
                                    WorkflowApprovalRecord.objects.create(start_time=datetime.now(),
                                                                          approver=approver[0].applicant,
                                                                          next=node_id['id'], status=0,
                                                                          order_number=index + 1,
                                                                          workflow_record_id=approver[0].id,
                                                                          next_approver=[])
                                else:
                                    WorkflowApprovalRecord.objects.create(start_time=datetime.now(),
                                                                          approver=approver[0].applicant,
                                                                          next=oneNode(approver[0].id, index + 1),
                                                                          status=0,
                                                                          order_number=index + 1,
                                                                          workflow_record_id=approver[0].id,
                                                                          next_approver=[])
                            d = by_form_pdf(nodeData[0].workflow_record_id)
                            nodeData.update(pdf=d)
                            xiaoxituisong(node_id['action'], request.user, nodeData[0].workflow_record_id)
                            reject_status(nodeData[0].workflow_record_id)
                            content['data'] = '駁回成功'
                            content['status'] = status.HTTP_200_OK
                            return content
                            # user_mail('您好,你有1筆員工事務等待簽核',approver[0].applicant,'你的已筆XXXX被駁回請重新申請')
                        elif string_comparison(nodePropety.reject_mode, 'AllowToSelect'):  # 駁回到某個節點組
                            if node_id['username']:
                                toMe = 0
                                WorkflowApprovalRecord.objects.filter(workflow_record_id=nodeData[0].workflow_record_id,
                                                                      next=nextID, order_number=index, status=0).update(
                                    status=10000, end_time=datetime.now())
                                nodeData.update(status=1, action='駁回', end_time=datetime.now(), desc=desc,
                                                signature=img)  # 更新記錄表
                                recName = Workflowrecord.objects.all().filter(id=nodeData[0].workflow_record_id)
                                nextRecord = WorkflowApprovalRecord.objects.all().filter(
                                    workflow_record_id=nodeData[0].workflow_record_id,
                                    order_number=int(nodeData[0].order_number) - 1)
                                if recName[0].applicant == username and nextRecord[0].action == "駁回":
                                    Workflowrecord.objects.filter(id=nodeData[0].workflow_record_id).update(status=1,
                                                                                                            end_time=datetime.now())
                                else:
                                    if node_id['username'] == '0':
                                        oneRecord = WorkflowApprovalRecord.objects.filter(
                                            workflow_record_id=nodeData[0].workflow_record_id).order_by('start_time')[0]
                                        node = [oneRecord]
                                        node_id['username'] = NodeGroup.objects.filter(
                                            workflowrecord_id=nodeData[0].workflow_record_id).order_by('order_number')[
                                            0].id
                                        toMe = 1
                                    else:
                                        node = NodeCase.objects.filter(group_id=node_id['username'],
                                                                       order_number=1)  # 查找nodecase實例
                                    for i in node:  # 遍歷寫入
                                        if int(node_id['type']):  # 判斷駁回后是否回到駁回者
                                            WorkflowApprovalRecord.objects.create(
                                                workflow_record_id=nodeData[0].workflow_record_id, status=0,
                                                approver=i.approver,
                                                next=node_id['id'],
                                                start_time=datetime.now(), order_number=index + 1)
                                        else:
                                            WorkflowApprovalRecord.objects.create(
                                                workflow_record_id=nodeData[0].workflow_record_id, status=0,
                                                approver=i.approver,
                                                next=oneNode(approver[0].id, index + 1),
                                                start_time=datetime.now(), order_number=index + 1)
                                d = by_form_pdf(nodeData[0].workflow_record_id)
                                nodeData.update(pdf=d)
                                xiaoxituisong(node_id['action'], request.user, nodeData[0].workflow_record_id)
                                reject_status(nodeData[0].workflow_record_id)
                                content['data'] = '駁回成功'
                                content['status'] = status.HTTP_200_OK
                                return content
                            else:
                                content['data'] = '請選擇駁回到指定節點'
                                content['status'] = status.HTTP_202_ACCEPTED
                                return content
                    elif string_comparison(node_id['action'], "forward"):  # 轉呈
                        if string_comparison(nodePropety.forward_mode, 'NoForward'):  # 是否支持轉呈
                            content['message'] = 'No forward'
                            content['status'] = status.HTTP_400_BAD_REQUEST
                        else:
                            forwardData = forward_(nextID, nodePropety, nodeData, node_id, index)
                            nodeData.update(status=1, action='轉呈', end_time=datetime.now(), desc=desc,
                                            signature=img)  # 更新記錄表
                            d = by_form_pdf(nodeData[0].workflow_record_id)
                            nodeData.update(pdf=d)
                            xiaoxituisong(node_id['action'], request.user, nodeData[0].workflow_record_id)
                            if forwardData:
                                content['data'] = forwardData
                                content['status'] = status.HTTP_202_ACCEPTED
                                return content
                            content['data'] = '轉呈成功'
                            content['status'] = status.HTTP_200_OK
                            return content
                    elif string_comparison(node_id['action'], "Abstain"):  # 轉呈
                        if string_comparison(nodePropety.user_mode, "action"):
                            nodeData.update(status=1, action='棄權', end_time=datetime.now(), desc=desc, signature=img)
                            # 下一個節點及發郵件通知
                            one_approval(nextID, index, nodeData[0].workflow_record_id, username)
                            d = by_form_pdf(nodeData[0].workflow_record_id)
                            nodeData.update(pdf=d)
                            xiaoxituisong(node_id['action'], request.user, nodeData[0].workflow_record_id)
                            content['data'] = '棄權'
                            content['status'] = status.HTTP_200_OK
                            return content
                        else:
                            content['data'] = '該節點無法棄權'
                            content['status'] = status.HTTP_202_ACCEPTED
                            return content
        # except Exception as e:
        #     WorkflowApprovalRecord.objects.filter(id=node_id['id']).update(status=0)
        #     content['status'] = status.HTTP_202_ACCEPTED
        #     # content['data'] = '請查看個信息是否完整，簽名檔是否存在'
        #     content['data'] = str(e)
        # finally:
            return content
    if request.method == "GET":
        try:
            wkRecord = Workflowrecord.objects.filter(applicant=username, status=0).all()
            content['data'] = []
            nodeApproval, nodeID = '', ''
            for record in wkRecord:
                workflow = Workflow.objects.filter(id=record.workflow_id).all()[0]
                recordApproval = WorkflowApprovalRecord.objects.filter(workflow_record_id=record.id, status=0).all()
                if recordApproval.count() > 1:
                    for row in recordApproval:
                        nodeApproval += row.approver + ' '
                elif recordApproval.count() == 1:
                    nodeApproval = recordApproval[0].approver
                    nodeID = recordApproval[0].approver
                else:
                    nodeApproval = ''
                stranded = str(datetime.now() - record.create_time).split(':')

                if 'days' in stranded[0]:
                    data = stranded[0].split('days')
                    stranded = data[0] + '天 ' + data[1].replace(',', '') + '小時 ' + stranded[1] + '分鐘 '
                    content['data'].append([record.id, record.no, workflow.name, record.applicant, record.create_time,
                                            [nodeApproval, nodeID], '待簽核',
                                            stranded, '緊急', record.desc, ''])
                else:
                    stranded = stranded[0] + '小時 ' + stranded[1] + '分鐘'
                    content['data'].append([record.no, workflow.name, record.applicant, record.create_time,
                                            [nodeApproval, recordApproval[0].id], '待簽核',
                                            stranded, '緊急' if int(stranded[0]) > 20 else '一般', record.desc, ''])
            content['status'] = status.HTTP_200_OK
        except Exception as e:
            content['status'] = status.HTTP_400_BAD_REQUEST
            content['message'] = str(e)
        finally:
            return content
    return content


@api_view(http_method_names=["GET", "PUT", "POST", "DELETE"])
@wrapp
@csrf_exempt
def workflow_approval_one(request, pk):
    content = {}
    if request.method == "GET":
        try:
            content['data'] = []
            client = request.META['HTTP_USER_AGENT']
            userName = request.user.username if request.user.username else 'ssssss'

            wkRecord = Workflowrecord.objects.filter(id=pk)
            from files.models import TbApplyform
            appType = TbApplyform.objects.filter(wrecord=pk).values('apply_type', 'card_id', 'name', "customer_id",
                                                                    "project_id", 'form_id')
            project = appType[0]["project_id"] or appType[0]["customer_id"]
            dqhr = []
            for record in wkRecord:
                userList = []
                for i in WorkflowApprovalRecord.objects.filter(workflow_record_id=record.id, status=1).all().order_by(
                        'order_number'):
                    if '[' in i.pdf and project:
                        pdf = eval(i.pdf) if i.pdf else []
                    elif "[" in i.pdf and not project:
                        pdf = eval(i.pdf)[0]
                    else:
                        pdf = i.pdf
                    name = User.objects.filter(username=i.approver).values('username', 'last_name', 'last_name')[0]
                    userList.append({'id': i.id, 'jon': name['username'], 'name': name['last_name'],
                                     'start_time': i.start_time.strftime('%Y-%m-%d %H:%M:%S') if i.start_time else '',
                                     'end_time': i.end_time.strftime('%Y-%m-%d %H:%M:%S') if i.end_time else '',
                                     'action': i.action, 'desc': i.desc,
                                     'pdf': [fi.replace(settings.MEDIA_ROOT, '/files/') for fi in
                                             pdf] if project else pdf.replace(settings.MEDIA_ROOT, '/files/'),
                                     'file': i.filename})
                approvalRecprd = WorkflowApprovalRecord.objects.filter(workflow_record_id=record.id,
                                                                       status=0).all().order_by('order_number')
                for i in approvalRecprd:
                    if '-' in i.next:
                        name = User.objects.filter(username=i.approver).values('username', 'last_name', 'last_name')[0]
                        group, node = i.next.split('-')
                        user = NodeCase.objects.filter(group_id=group, order_number=1 if node == '0' else node)[0]
                        user_role = user.user_role_list if user.user_role_list else user.user_choose
                        array = []
                        if user_role:
                            for row in eval(user_role):
                                to_user = User.objects.filter(username=row)[0]
                                array.append({"UserName": to_user.last_name, "UserID": to_user.username})
                        userdata = {'id': i.id, 'name': name['last_name'], 'jon': name['username'], 'user_list': array,
                                    'start_time': i.start_time.strftime('%Y-%m-%d %H:%M:%S') if i.start_time else '',
                                    'end_time': i.end_time.strftime('%Y-%m-%d %H:%M:%S') if i.end_time else '',
                                    'action': '待簽核', 'img': i.signature, "forward_mode": False}
                        dqhr.append(name['username'])
                        userdata["forward_list"] = []
                        if string_comparison(user.forward_mode, 'ByUsers'):
                            userdata["forward_mode"] = True
                            for i in eval(user.forward_list):
                                i2, name2 = by_agent(i, appType[0]["form_id"])
                                ur = User.objects.filter(username=i)
                                if i2 == i:

                                    userdata["forward_list"].append(
                                        {'UserID': ur[0].username, 'UserName': ur[0].last_name})
                                else:
                                    userdata["forward_list"].append(
                                        {'UserID': i2, 'UserName': name2})
                        elif string_comparison(user.forward_mode, 'AnyOne'):
                            userdata["forward_mode"] = True
                            userdata["forward_list"] = []
                        userList.append(userdata)
                    else:
                        name = User.objects.filter(username=i.approver).values('username', 'last_name', 'last_name')[0]
                        userdata = {'id': i.id, 'name': name['last_name'], 'jon': name['username'], 'user_list': [],
                                    'start_time': i.start_time.strftime('%Y-%m-%d %H:%M:%S') if i.start_time else '',
                                    'end_time': i.end_time.strftime('%Y-%m-%d %H:%M:%S') if i.end_time else '',
                                    'action': '待簽核', 'img': i.signature, "forward_mode": False}
                        dqhr.append(name['username'])
                        userList.append(userdata)
                actionList, rejected_list = [], []
                if userName in dqhr:
                    if approvalRecprd:
                        action = \
                            WorkflowApprovalRecord.objects.filter(
                                workflow_record_id=approvalRecprd[0].workflow_record_id,
                                order_number=approvalRecprd[0].order_number - 1)[0].action
                        if '-' in approvalRecprd[0].next and action != "駁回":
                            group, num = approvalRecprd[0].next.split('-')
                            node = NodeCase.objects.filter(order_number=1 if num == '0' else num, group_id=group)
                            # action = {'pass':'通過','rejected':'駁回'}
                            actionList.append({'name': '通過', 'action': 'pass'})
                            if string_comparison(node[0].user_mode, 'AnyOne'):
                                actionList.append({'name': '棄權', 'action': 'giveup'})
                            if node[0].forward_mode:
                                if not string_comparison(node[0].forward_mode, 'NoForward'):
                                    actionList.append({'name': '轉呈', 'action': 'forward'})
                            if string_comparison(node[0].reject_mode, 'ToApplicant'):
                                actionList.append({'name': '駁回', 'action': 'rejected'})
                            if string_comparison(node[0].reject_mode, 'AllowToSelect'):
                                rejected_list = [{'UserName': i.name, 'UserID': i.id} for i in
                                                 NodeGroup.objects.filter(id__lt=group, workflowrecord_id=pk) if
                                                 i.group.count() > 0]
                                rejected_list.insert(0, {'UserName': '駁回到發起者', 'UserID': 0})
                                actionList.append({'name': '駁回', 'action': 'rejected'})
                        else:
                            if userName == Workflowrecord.objects.filter(id=approvalRecprd[0].workflow_record_id)[
                                0].applicant:
                                actionList.append({'name': '重新發起', 'action': 'pass'})
                                actionList.append({'name': '取消申請', 'action': 'rejected'})
                            else:
                                actionList.append({'name': '通過', 'action': 'pass'})
                                actionList.append({'name': '駁回', 'action': 'rejected'})
                    if rejected_list:
                        for i in userList:
                            if i['action'] == '待簽核':
                                i['reject_list'] = rejected_list
                    content['data'].append(
                        {'no': appType[0]['card_id'], 'name': appType[0]['name'], 'username': record.username,
                         'applicant': record.applicant, 'id': approvalRecprd[0].id,
                         'rectime': record.create_time.strftime('%Y-%m-%d %H:%M:%S') if record.create_time else '',
                         'record': userList, 'property': actionList})
                else:
                    content['data'].append(
                        {'no': appType[0]['card_id'], 'name': appType[0]['name'], 'username': record.username,
                         'applicant': record.applicant,
                         'rectime': record.create_time.strftime('%Y-%m-%d %H:%M:%S') if record.create_time else '',
                         'record': userList})

                if 'Mobile'.lower() in client.lower() or 'iPHONE'.lower() in client.lower() or 'iPad'.lower() in client.lower() or 'android'.lower() in client.lower():
                    pass
                else:
                    if string_comparison('False', appType[0]['apply_type']):
                        pass
                    else:
                        content['data'][0]['property'] = []
                        content['data'][0]['tip'] = 'APP簽核'
            content['status'] = status.HTTP_200_OK
        except Exception as e:
            content['status'] = status.HTTP_400_BAD_REQUEST
            content['data'] = str(e)
        finally:
            return content


@api_view(http_method_names=["GET", "PUT", "POST", "DELETE"])
@wrapp
def reminder(request):
    """
    催單
    :param request:
    :return:
    """
    content = {}
    user = request.user
    if request.method == "POST":
        try:
            from tb_forms.models import TbApplyform
            data = request.data
            apply = TbApplyform.objects.filter(id=data['id'])
            if apply:
                apply = apply[0]
            else:
                content['status'] = status.HTTP_202_ACCEPTED
                content['data'] = "該表單異常"
                return content
            if Workflowrecord.objects.values('id').filter(id=apply.wrecord_id, status=1):
                content['status'] = status.HTTP_202_ACCEPTED
                content['data'] = "該記錄已簽核完成"
                return ''
            log = ReminderLog.objects.filter(no=apply.card_id).exclude(num=0).order_by('-rectime')
            if log:
                times = str(datetime.now() - log[0].rectime).split(':')[0]
                if 'day' in times or 'days' in times:
                    times = 5
            else:
                times = 1
            remList = []
            if int(times) >= 1:
                approval = WorkflowApprovalRecord.objects.filter(workflow_record_id=apply.wrecord_id).exclude(
                    status=0).order_by('-end_time')
                if approval:
                    actiondict = {'通過': 'pass', '駁回': 'rejected', '轉呈': 'forward', '棄權': 'giveup', '發起': ''}
                    action = actiondict[approval[0].action]
                    current = approval[0].end_time
                    username = approval[0].username if approval[0].username else ''
                    approval = username + '(' + approval[0].approver + ')'
                else:
                    approval = apply.applicant + '(' + User.objects.filter(username=apply.applicant)[0].last_name + ')'
                    current = apply.apply_time
                    action = "pass"
                for node in WorkflowApprovalRecord.objects.filter(workflow_record_id=apply.wrecord_id, status=0):
                    username = node.username if node.username else ''
                    cuidan = {'type': 'cuidan',
                              'from': apply.applicant + '(' + User.objects.filter(username=apply.applicant)[
                                  0].last_name + ')',
                              'to': username + '(%s)' % node.approver,
                              'date': datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
                              'message': {'no': apply.card_id, 'type': "催單動態",
                                          'time': datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
                                          'title': "【表單簽核】您有一筆表單需要簽核",
                                          'url': "../templates/module1/index.html#/form:355" + str(apply.id)},
                              'content': [{'form_id': apply.id, 'form_no': apply.card_id,
                                           'form_name': apply.name,
                                           'initial_date': apply.apply_time.strftime('%Y-%m-%d %H:%M:%S'),
                                           'current_approver': approval,
                                           'current_approve_date': current.strftime('%Y-%m-%d %H:%M:%S'),
                                           'current_approve_status': action, 'current_approve_comment': str(apply.desc),
                                           'next_approver': username + '(%s)' % node.approver, 'status': 'open'}]}
                    log = ReminderLog.objects.create(no=apply.card_id, rectime=datetime.now(),
                                                     applicant=request.user.username,
                                                     user=username + '(%s)' % node.approver, name=user.last_name,
                                                     title=cuidan['message']['title'],
                                                     type=cuidan['message']['type'], url=cuidan['message']['url'],
                                                     status=0, num=1)
                    cuidan['message']['id'] = log.id
                    # message = threading.Thread(target=cccc,args=(str(cuidan)))
                    # message.setDaemon(True)
                    # message.start()

                    cccc(str(cuidan))

                content['status'] = status.HTTP_200_OK
                content['data'] = "催單成功"
                return content
            else:
                content['status'] = status.HTTP_202_ACCEPTED
                content['data'] = "催單太過頻繁，請稍後再試"
                return content
        except Exception as e:
            content['status'] = status.HTTP_202_ACCEPTED
            content['data'] = str(e)
            return content

    if request.method == "GET":
        try:
            userName = 'F1330320'  # request.session['username']
            wkRecord = Workflowrecord.objects.filter(applicant=userName, status=0).all()
            content['data'] = []
            nodeApproval = ''
            for record in wkRecord:
                workflow = Workflow.objects.filter(id=record.workflow_id).all()[0]
                recordApproval = WorkflowApprovalRecord.objects.filter(workflow_record_id=record.id, status=0).all()
                if recordApproval.count() > 1:
                    for row in recordApproval:
                        nodeApproval += row.approver + ' '
                elif recordApproval.count() == 1:
                    nodeApproval = recordApproval[0].approver
                else:
                    nodeApproval = ''
                stranded = str(datetime.now() - record.create_time).split(':')

                if 'days' in stranded[0]:
                    data = stranded[0].split('days')
                    stranded = data[0] + '天 ' + data[1].replace(',', '') + '小時 ' + stranded[1] + '分鐘 '
                    content['data'].append(
                        [record.no, workflow.name, record.applicant, record.create_time, nodeApproval, '待簽核',
                         stranded, '緊急', record.desc, ''])
                else:
                    stranded = stranded[0] + '小時 ' + stranded[1] + '分鐘 '
                    content['data'].append(
                        [record.no, workflow.name, record.applicant, record.create_time, nodeApproval, '待簽核',
                         stranded, '緊急' if int(stranded[0]) > 20 else '一般', record.desc, ''])

            content['status'] = status.HTTP_200_OK
        except Exception as e:
            content['status'] = status.HTTP_202_ACCEPTED
            content['message'] = str(e)
    return content


# @login_check
@api_view(http_method_names=["GET", "PUT", "POST", "DELETE"])
@wrapp
@csrf_exempt
def agent(request):
    """
    代理人
    :param request:
    :return:
    """
    content = {}
    # userName= models.LoginToken.objects.filter(token=request.META["HTTP_X_CSRFTOKEN"])[0].user_id
    userName = request.user.username

    if request.method == "POST":
        try:
            null = ""
            data = eval(request.data['data'])
            try:
                with transaction.atomic():
                    # if WfsAgent.objects.filter(agent=request.user.id):
                    #     content['status'] = status.HTTP_202_ACCEPTED
                    #     content['data'] = ''
                    #     return content
                    if datetime.strptime(data['start_time'], '%Y-%m-%d  %H:%M:%S') > datetime.strptime(data['end_time'],
                                                                                                       '%Y-%m-%d  %H:%M:%S'):
                        content['status'] = status.HTTP_202_ACCEPTED
                        content['data'] = '開始時間必須小於結束時間'
                        return content
                    elif datetime.strptime(data['start_time'], '%Y-%m-%d  %H:%M:%S') < datetime.now():
                        content['status'] = status.HTTP_202_ACCEPTED
                        content['data'] = '開始時間大於當前時間'
                        return content
                    else:
                        workflowAgent = WorkflowAgent.objects.filter(user_agent=data['user_agent_id'],
                                                                     end_time__gt=datetime.strptime(data['start_time'],
                                                                                                    '%Y-%m-%d %H:%M:%S'))
                        if not len(workflowAgent):
                            tub = WorkflowAgent.objects.create(user_agent_id=data['user_agent_id'],
                                                               start_time=datetime.strptime(data['start_time'],
                                                                                            '%Y-%m-%d  %H:%M:%S'),
                                                               end_time=datetime.strptime(data['end_time'],
                                                                                          '%Y-%m-%d  %H:%M:%S'),
                                                               status=0, rectime=datetime.now(),
                                                               form_list={
                                                                   'name': data['tmpls_Gen'][1] + data['tmpls_Att'][1],
                                                                   'id': data['tmpls_Gen'][0] + data['tmpls_Att'][0]})
                        else:
                            content['status'] = status.HTTP_202_ACCEPTED
                            content['data'] = '該段時間內已設有代理'
                            return content
            except Exception as e:
                content['status'] = status.HTTP_202_ACCEPTED
                content['data'] = '添加失敗'
                return content
            agent = WfsAgent.objects.filter(id=data['user_agent_id']).values('agent__username', 'agent__last_name')[0]
            cuidan = {'type': 'cuidan', 'from': request.user.last_name + '(' + userName + ')',
                      'to': agent['agent__last_name'] + "(" + agent["agent__username"] + ")",
                      'date': datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
                      'message': {'type': "代理動態", 'time': datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
                                  'title': "【工作代理】" + request.user.last_name + '(' + userName + ')' + "將你設為代理人",
                                  'url': "../templates/module1/index.html#/agented:" + str(tub.id)},
                      'content': []}
            ReminderLog.objects.create(no='', rectime=datetime.now(), applicant=request.user.username,
                                       user=agent['agent__last_name'] + "(" + agent["agent__username"] + ")",
                                       name=request.user.last_name, title=cuidan['message']['title'],
                                       type=cuidan['message']['type'], url=cuidan['message']['url'], status=0, num=1)
            message = threading.Thread(target=cccc, args=(str(cuidan)))
            message.setDaemon(True)
            message.start()

            content['status'] = status.HTTP_201_CREATED
            content['data'] = '添加成功'
        except Exception as e:
            content['status'] = status.HTTP_202_ACCEPTED
            content['message'] = str(e)
        finally:
            return content
    if request.method == "GET":
        try:
            agent = request.GET['agent']
            meList = []
            if int(agent):
                me = WorkflowAgent.objects.filter(user_agent__agent__username=userName).values('id', 'user_agent__user',
                                                                                               'user_agent__username',
                                                                                               'rectime',
                                                                                               'user_agent__org__org_name',
                                                                                               'start_time', 'end_time',
                                                                                               'status')
                for i in me:
                    meList.append({'id': i['id'], 'name': i['user_agent__username'], 'jon': i['user_agent__user'],
                                   'rectime': i['rectime'].strftime('%Y-%m-%d %H:%M:%S'),
                                   'org': i['user_agent__org__org_name'],
                                   'start': i['start_time'].strftime('%Y-%m-%d %H:%M:%S'),
                                   'end': i['end_time'].strftime('%Y-%m-%d %H:%M:%S'),
                                   'status': 'Valid' if i['end_time'] > datetime.now() else 'Invalid'})
            else:
                me = WorkflowAgent.objects.filter(user_agent__user=userName).values('id', 'user_agent__user',
                                                                                    'user_agent__username',
                                                                                    'rectime',
                                                                                    'user_agent__org__org_name',
                                                                                    'user_agent__agent__username',
                                                                                    'user_agent__agent__last_name',
                                                                                    'start_time', 'end_time', 'status')
                for i in me:
                    meList.append({'id': i['id'], 'name': i['user_agent__agent__last_name'],
                                   'jon': i['user_agent__agent__username'],
                                   'rectime': i['rectime'].strftime('%Y-%m-%d %H:%M:%S'),
                                   'org': i['user_agent__org__org_name'],
                                   'start': i['start_time'].strftime('%Y-%m-%d %H:%M:%S'),
                                   'end': i['end_time'].strftime('%Y-%m-%d %H:%M:%S'),
                                   'status': 'Valid' if i['end_time'] > datetime.now() else 'Invalid'})
            content['data'] = meList
            content['status'] = status.HTTP_200_OK
        except Exception as e:
            content['status'] = status.HTTP_202_ACCEPTED
            content['message'] = str(e)
        finally:
            return content


@api_view(http_method_names=["GET", "PUT", "POST", "DELETE"])
@wrapp
@csrf_exempt
def user_org(request):
    """
    獲取當前用戶Org
    :param request:
    :return:
    """
    content = {}
    if request.method == "GET":
        try:
            user = request.user
            org = request.GET.get("org", "")
            userOrg = [int(org)] if org else UserOrg.objects.filter(user_id=user.id)
            if userOrg:
                userOrgLevel = []
                for i in userOrg:
                    if type(i) == int:
                        org = i
                    else:
                        org = i.org_id
                    org = Org.objects.filter(id=org).values('id', 'org_name', 'org_code')
                    if org:
                        userOrgLevel.append(
                            {'org': org[0]['org_name'], 'org_id': org[0]['id'], 'code': org[0]['org_code']})
                        wfsAgent = WfsAgent.objects.filter(user=user.username, org_id=org[0]['id'], enabled=1).values(
                            'agent__last_name', 'id', 'agent__username')
                        if len(wfsAgent):
                            userOrgLevel[len(userOrgLevel) - 1]['user_list'] = []
                            for i in wfsAgent:
                                userOrgLevel[len(userOrgLevel) - 1]['user_list'].append(
                                    {'name': i['agent__last_name'], 'jon': i['agent__username'], 'id': i['id']})
                    else:
                        content['status'] = status.HTTP_202_ACCEPTED
                        content['data'] = "請查看組織是否合法"
                        return content
            else:
                content['status'] = status.HTTP_202_ACCEPTED
                content['data'] = "請查看是否在組織內"
                return content
            content['status'] = status.HTTP_200_OK
            content['data'] = {'data': userOrgLevel, 'jon': user.username, 'name': user.last_name}
        except Exception as e:
            content['status'] = status.HTTP_202_ACCEPTED
            content['message'] = str(e)
        finally:
            return content
    if request.method == "POST":
        try:
            agent_id = request.data
            if WorkflowAgent.objects.filter(id=agent_id['id'])[0].status:
                content['status'] = status.HTTP_202_ACCEPTED
                content['data'] = '此單為已簽核單'
                return content
            else:
                if string_comparison(agent_id['status'], 'True'):
                    WorkflowAgent.objects.filter(id=agent_id['id']).update(status=1, action=1)
                    content['data'] = "簽核成功"
                    content['status'] = status.HTTP_200_OK
                else:
                    WorkflowAgent.objects.filter(id=agent_id['id']).update(status=1, action=0)
                    content['data'] = "駁回成功"
                    content['status'] = status.HTTP_200_OK
        except Exception as e:
            content['status'] = status.HTTP_202_ACCEPTED
            content['message'] = str(e)
        finally:
            return content


# @login_check
@api_view(http_method_names=["GET", "PUT", "POST", "DELETE"])
@wrapp
@csrf_exempt
def agent_one(request, pk):
    content = {}
    userName = request.user.username
    userName = User.objects.filter(username=userName).all()[0]
    if request.method == "POST":
        try:
            data = request.data
            userAgentID = data['user_agent_id']
            startTime = data['start_time']
            endTime = data['end_time']
            WorkflowAgent.objects.create(user_agent_id=userAgentID, start_time=startTime, end_time=endTime)
            content['status'] = status.HTTP_200_OK
            content['data'] = '添加成功'
        except Exception as e:
            content['status'] = status.HTTP_202_ACCEPTED
            content['message'] = str(e)
    if request.method == "PUT":
        try:
            data = request.data
            id = pk
            WorkflowAgent.objects.filter(id=id).update(start_time='2000-08-18 10:26:29', end_time='2000-08-19 15:00:00')
            content['status'] = status.HTTP_200_OK
            content['data'] = '更新成功'
        except Exception as e:
            content['status'] = status.HTTP_202_ACCEPTED
            content['message'] = str(e)
    if request.method == "GET":
        try:
            data = []
            for i in WorkflowAgent.objects.values('user_agent__username', 'user_agent__user',
                                                  'user_agent__agent__last_name', 'start_time', 'end_time'):
                i['end_time'] = i['end_time'].strftime('%Y-%m-%d %H:%M:%S')
                i['start_time'] = i['start_time'].strftime('%Y-%m-%d %H:%M:%S')
                data.append(i)
            content['data'] = data  # AgentUser.objects.values('user','agent','start_time','end_time')
            content['status'] = status.HTTP_200_OK
        except Exception as e:
            content['status'] = status.HTTP_202_ACCEPTED
            content['message'] = str(e)
    if request.method == "DELETE":
        try:
            WorkflowAgent.objects.filter(id=pk).delete()
            content['status'] = status.HTTP_204_NO_CONTENT
            content['data'] = '刪除成功'
        except Exception as e:
            content['status'] = status.HTTP_202_ACCEPTED
            content['message'] = str(e)
    return content


# @login_check
@api_view(http_method_names=["GET", "PUT", "POST", "DELETE"])
@wrapp
@csrf_exempt
def agent_config(request):
    """
    代理人配置
    :param request:
    :return:
    """
    userName = request.user.username
    name = request.user.last_name
    content = {}
    if request.method == "POST":
        try:
            data = request.data
            agent = data['agent']
            org = data['org']
            user_id = User.objects.filter(username=agent, status_id=100)
            if user_id:
                user_id = user_id[0]
                if userName == user_id.username:
                    content['status'] = status.HTTP_202_ACCEPTED
                    content['data'] = "代理人不能是自己"
                    return content
            else:
                content['status'] = status.HTTP_202_ACCEPTED
                content['data'] = "未找到該用戶"
                return content
            if WfsAgent.objects.filter(user=userName, agent_id=user_id, org_id=org, enabled=1):
                content['status'] = status.HTTP_202_ACCEPTED
                content['data'] = "該同仁已經是本職位的常用代理"
                return content
            if len(WfsAgent.objects.filter(user=userName, org_id=org, enabled=1)) <= 2:
                WfsAgent.objects.create(user=userName, username=name, agent_id=user_id.id, org_id=org, enabled=True,
                                        rectime=datetime.now())
                content['status'] = status.HTTP_201_CREATED
                content['data'] = "添加成功"
            else:
                content['status'] = status.HTTP_202_ACCEPTED
                content['data'] = "單個職務常用代理人最多為三人"
        except Exception as e:
            content['status'] = status.HTTP_202_ACCEPTED
            content['message'] = str(e)
    if request.method == "GET":
        try:
            agentList = []
            for i in WfsAgent.objects.filter(user=userName, enabled=True).values('id', 'user', 'username',
                                                                                 "agent__last_name", "agent__username",
                                                                                 'org__org_name', 'rectime', 'update'):
                agentList.append(
                    {'id': i['id'], 'jon': i['user'], 'name': i['username'], 'agent_jon': i["agent__username"],
                     'agent_name': i['agent__last_name'], 'org': i['org__org_name'],
                     'rectime': i['rectime'].strftime('%Y-%m-%d %H:%M:%S'),
                     'update': i['update'].strftime('%Y-%m-%d %H:%M:%S') if i['update'] else ''})
            content['data'] = agentList
            content['status'] = status.HTTP_200_OK
        except Exception as e:
            content['status'] = status.HTTP_202_ACCEPTED
            content['message'] = str(e)
    return content


# @login_check
@api_view(http_method_names=["GET", "PUT", "POST", "DELETE"])
@wrapp
@csrf_exempt
def agent_config_one(request, pk):
    """
    代理人配置
    :param request:
    :return:
    """
    content = {}
    if request.method == "GET":
        try:
            content['data'] = WfsAgent.objects.filter(id=pk, enabled=True).values('id', 'user', 'username',
                                                                                  "agent__last_name",
                                                                                  "org__org_level__duty", "org")
            content['status'] = status.HTTP_200_OK
        except Exception as e:
            content['status'] = status.HTTP_202_ACCEPTED
            content['message'] = str(e)
    if request.method == "PUT":
        try:
            data = request.data
            id = pk
            agent = data['agent']
            org = data['org']
            WfsAgent.objects.filter(id=id).update(agent=agent, org_id=org, enabled=True)
            content['status'] = status.HTTP_200_OK
            content['data'] = "更新成功"
        except Exception as e:
            content['status'] = status.HTTP_202_ACCEPTED
            content['message'] = str(e)
    if request.method == "DELETE":
        try:
            id = pk
            WfsAgent.objects.filter(id=id).update(enabled=False)
            content['status'] = status.HTTP_204_NO_CONTENT
            content['data'] = "刪除成功"
        except Exception as e:
            content['status'] = status.HTTP_202_ACCEPTED
            content['message'] = str(e)
    return content


@api_view(http_method_names=["GET", "PUT", "POST", "DELETE"])
@wrapp
@csrf_exempt
def agent_approval(request):
    content = {}
    userName = request.user.username
    if request.method == "GET":
        try:
            content['data'] = NodeCase.objects.values('group_id', 'order_number').exclude(agent='').filter(
                Q(approval=userName) | Q(agent=userName))
            content['status'] = status.HTTP_200_OK
        except Exception as e:
            content['status'] = status.HTTP_202_ACCEPTED
            content['message'] = str(e)
        finally:
            return content


@api_view(http_method_names=["GET", "PUT", "POST", "DELETE"])
@wrapp
@csrf_exempt
def from_approver(request, pk):
    content = {}
    if request.method == "GET":
        try:
            data = ByFromApprover.objects.values('time', 'typename', 'typeid', 'name', 'starttime', 'endtime',
                                                 'approver_record').filter(typeid=pk)
            data2 = []
            if len(data):
                for i in data:
                    i['time'] = round(i['time'], 2)
                    i['starttime'] = i['starttime'].strftime('%Y-%m-%d %H:%M:%S')
                    i['endtime'] = i['endtime'].strftime('%Y-%m-%d %H:%M:%S')
                    data2.append(i)
                content['data'] = data2
                content['status'] = status.HTTP_200_OK
            else:
                content['data'] = "該分類暫時沒有簽核記錄"
                content['status'] = status.HTTP_200_OK
        except Exception as e:
            content['status'] = status.HTTP_202_ACCEPTED
            content['message'] = str(e)
        finally:
            return content


@api_view(http_method_names=["GET", "PUT", "POST", "DELETE"])
@wrapp
@csrf_exempt
def approver_from(request):
    content = {}
    if request.method == "GET":
        try:
            data2 = []
            data = ByFromApprover2.objects.values('time', 'typename', 'typeid', 'name', 'starttime', 'endtime',
                                                  "approver_record")
            if len(data):
                for i in data:
                    i['time'] = round(i['time'], 2)
                    i['starttime'] = i['starttime'].strftime('%Y-%m-%d %H:%M:%S')
                    i['endtime'] = i['endtime'].strftime('%Y-%m-%d %H:%M:%S')
                    data2.append(i)
                content['data'] = data2
                content['status'] = status.HTTP_200_OK
            else:
                content['data'] = "該分類暫時沒有簽核記錄"
                content['status'] = status.HTTP_200_OK
        except Exception as e:
            content['status'] = status.HTTP_202_ACCEPTED
            content['message'] = str(e)
        finally:
            return content


@api_view(http_method_names=["GET", "PUT", "POST", "DELETE"])
@wrapp
@csrf_exempt
def approver_from2(request):
    content = {}
    if request.method == "GET":
        try:
            username = request.GET['username']
            type_id = request.GET['type_id']
            if username:
                data = ByFromApprover.objects.values('time', 'typename', 'typeid', 'name', 'starttime',
                                                     'endtime').filter(approver_record=username, typeid=type_id)
                data2 = []
                if len(data):
                    for i in data:
                        i['time'] = round(i['time'], 2)
                        i['starttime'] = i['starttime'].strftime('%Y-%m-%d %H:%M:%S')
                        i['endtime'] = i['endtime'].strftime('%Y-%m-%d %H:%M:%S')
                        data2.append(i)
                    content['data'] = data2
                    content['status'] = status.HTTP_200_OK
                else:
                    content['data'] = "該分類暫時沒有簽核記錄"
                    content['status'] = status.HTTP_200_OK
            else:
                content['data'] = "該用戶不存在"
                content['status'] = status.HTTP_200_OK
        except Exception as e:
            content['status'] = status.HTTP_202_ACCEPTED
            content['message'] = str(e)
        finally:
            return content


@api_view(http_method_names=["GET", "PUT", "POST", "DELETE"])
@wrapp
@csrf_exempt
def from_type(request):
    content = {}
    if request.method == "GET":
        try:
            sta = request.GET.get('status')
            data = ByFromType.objects.values('name', 'types', 'time', 'starttime', 'endtime').order_by('time')
            if sta:
                if len(data) >= 20:
                    da = 20
                else:
                    da = len(data)
                value, name = [], []
                for i in range(da):
                    value.append(round(data[i]['time'], 2))
                    name.append(data[i]['name'])
                content['data'] = {'value': value, 'name': name}
                content['status'] = status.HTTP_200_OK
            else:
                data2 = []
                if len(data):
                    for i in data:
                        i['time'] = round(i['time'], 2)
                        i['starttime'] = i['starttime'].strftime('%Y-%m-%d %H:%M:%S')
                        i['endtime'] = i['endtime'].strftime('%Y-%m-%d %H:%M:%S')
                        data2.append(i)
                    content['data'] = data
                    content['status'] = status.HTTP_200_OK
                else:
                    content['data'] = "暫時沒有簽核記錄"
                    content['status'] = status.HTTP_200_OK
        except Exception as e:
            content['status'] = status.HTTP_202_ACCEPTED
            content['message'] = str(e)
        finally:
            return content


@api_view(http_method_names=["GET", "PUT", "POST", "DELETE"])
@wrapp
def from_node(request):
    content = {}
    if request.method == "GET":
        try:
            data = list(ByNode.objects.values('name', 'approver_record', 'time').order_by('-time')[:20])

            if len(data):
                for i in data:
                    if not i['time']:
                        da = data.index(i)
                        data.pop(da)
                    else:
                        i['time'] = round(i['time'], 2)

                content['data'] = data
                content['status'] = status.HTTP_200_OK
            else:
                content['data'] = "暫時沒有簽核記錄"
                content['status'] = status.HTTP_200_OK
        except Exception as e:
            content['status'] = status.HTTP_202_ACCEPTED
            content['message'] = str(e)
        finally:
            return content


@api_view(http_method_names=["GET", "PUT", "POST", "DELETE"])
@wrapp
def from_month(request):
    content = {}
    if request.method == "GET":
        try:

            dateList = every_day_of_month()
            data = ByFromTypeMonth.objects.values('type_name', 'time', 'date').filter(
                date__month=datetime.today().month)
            typename = [i['name'] for i in ByFromType.objects.values('name')]
            dataList = []
            if len(data):
                index = 0
                # for i in typename:
                for date in typename:
                    dic = {}
                    dic['name'] = date
                    dic['type'] = 'line'
                    sss = []
                    for index, row in enumerate(dateList, 1):
                        for r in data:
                            if r['type_name'] == date:
                                if row == r['date'] and r['type_name'] == date:
                                    sss.append(round(r['time'], 2))
                        if index > len(sss):
                            sss.append(0)
                    dic['data'] = sss
                    dataList.append(dic)
                    # for row in typename:
                    #     dataList[index][row] = ''
                    # for row in data:
                    #     if row['date'] == date:
                    #         dataList[index][row['type_name']] = row['time']
                    # if not dataList[index]:
                    #     dataList[index] = ''
                    # index += 1
                content['data'] = {"valus": dataList, "date": dateList}
                content['status'] = status.HTTP_200_OK
            else:
                content['data'] = "暫時沒有簽核記錄"
                content['status'] = status.HTTP_200_OK
        except Exception as e:
            content['status'] = status.HTTP_202_ACCEPTED
            content['message'] = str(e)
        finally:
            return content


from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger


@api_view(http_method_names=["GET", "PUT", "POST", "DELETE"])
@wrapp
def mqtt(request):
    """
    MQTT
    :param request:
    :return:
    """
    content = {}
    userName = request.user.username
    if request.method == "GET":
        try:
            log = []
            message_type = request.GET['type']
            page = request.GET['page']
            key = request.GET.get('select', '')
            if message_type == 'wait':
                message_status = [0]
            elif message_type == 'done':
                message_status = [1]
            elif message_type == 'all':
                message_status = [0, 1]
            if not key:
                data = ReminderLog.objects.filter(user__icontains=userName,
                                                  status__in=message_status).values().order_by('-rectime')
            else:
                data = ReminderLog.objects.filter(user__icontains=userName,
                                                  status__in=message_status).values().filter(
                    Q(name__icontains=key) | Q(title__icontains=key) | Q(type__icontains=key)).order_by('-rectime')
            if page:
                paginator = Paginator(data, 20)
            else:
                paginator = Paginator(data, len(log))
                page = 1
            for i in paginator.page(page):
                i['time'] = i['rectime'].strftime('%Y-%m-%d %H:%M:%S')
                log.append(i)
            content['data'] = log
            content['page'] = {'count': paginator.count, 'page': page, 'page_count': paginator.page_range[-1]}
            content['status'] = status.HTTP_200_OK
        except Exception as e:
            content['status'] = status.HTTP_202_ACCEPTED
            content['message'] = str(e)
        finally:
            return content


@api_view(http_method_names=["GET", "PUT", "POST", "DELETE"])
@wrapp
def mqtt2(request, pk):
    """
    MQTT
    :param request:
    :return:
    """
    content = {}
    userName = request.user.username
    if request.method == "GET":
        try:
            content['data'] = ReminderLog.objects.filter(user__icontains=userName, status=1, id=pk).values()
            content['status'] = status.HTTP_200_OK
        except Exception as e:
            content['status'] = status.HTTP_202_ACCEPTED
            content['message'] = str(e)
        finally:
            return content
    if request.method == "PUT":
        try:
            data = ReminderLog.objects.filter(user__icontains=userName, status=0, id=pk)
            if data:
                data.update(status=1)
                content['data'] = '成功'
                content['status'] = status.HTTP_200_OK
            else:
                content['status'] = status.HTTP_202_ACCEPTED
                content['message'] = '未找到該記錄'
        except Exception as e:
            content['status'] = status.HTTP_202_ACCEPTED
            content['message'] = str(e)
        finally:
            return content
    if request.method == "DELETE":
        try:
            data = ReminderLog.objects.filter(user__icontains=userName, status=1, id=pk)
            if data:
                data.delete()
                content['data'] = '成功'
                content['status'] = status.HTTP_200_OK
            else:
                content['status'] = status.HTTP_202_ACCEPTED
                content['message'] = '未找到該記錄'
        except Exception as e:
            content['status'] = status.HTTP_202_ACCEPTED
            content['message'] = str(e)
        finally:
            return content
